package com.ding.easycontroller.utils;

import com.ding.easycontroller.work.Controller;
import com.ding.easycontroller.work.Service;
import com.ding.easycontroller.service.ControllerService;
import com.ding.easycontroller.service.ServiceService;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ScriptUtils {

/*
    private static String path;

    private static ControllerService controllerService;
    private static ServiceService moduleService;

    public static void initScript(String path, ControllerService controllerService, ServiceService moduleService) {
        ScriptUtils.path = path;
        ScriptUtils.controllerService = controllerService;
        ScriptUtils.moduleService = moduleService;

        File file = new File(path);
        if (!file.exists()) {
            //构建目录
            if (!file.mkdir()) {
                throw new RuntimeException("无法初始化目录:" + path);
            }
        }

        //找到所有脚本文件
        File[] files = file.listFiles();

        if (files != null) {

            List<Element> controllers = new ArrayList<>();
            List<Element> modules = new ArrayList<>();

            //对文件进行分类
            type(controllers, modules, files);


            List<Service> ms = new ArrayList<>();

            List<Controller> cs = new ArrayList<>();

            //将模组读取出来
            for (Element module : modules) {
                handleModule(module, ms);
            }

            for (Element controller : controllers) {
                handleController(controller, cs);
            }

            //判断去重
            List<Service> mss = new ArrayList<>();

            for (Service m : ms) {
                if (mss.contains(m)) {
                    throw new RuntimeException("重复module:" + m.getName());
                }
                mss.tryAdd(m);

            }

            List<Controller> css = new ArrayList<>();

            for (Controller c : cs) {
                if (css.contains(c)) {
                    throw new RuntimeException("重复controller:" + c.getUri() + "-" + c.getMethod());
                }
                css.tryAdd(c);
            }


            //遍历添加
            for (Service m : mss) {
                moduleService.tryAdd(m);
            }

            for (Controller controller : css) {
                controllerService.tryAdd(controller);
            }

        }

    }



    //获取并进行分类
    private static void type(List<Element> controllers, List<Element> modules, File[] files) {
        for (File file : files) {
            if (file.getName().endsWith(".script")) {
                Element element = readElement(file);

                if (element != null) {
                    String name = element.getName();
                    switch (name) {
                        case "controller":
                            controllers.tryAdd(element);
                            break;
                        case "module":
                            modules.tryAdd(element);
                            break;
                    }
                }
            }
        }
    }


    private static void handleModule(Element element, List<Service> modules) {
        Service module = new Service();
        Element name = element.getChild("name");
        module.setName(name.getText());
        Element js = element.getChild("js");
        module.setJs(js.getText());
        Element description = element.getChild("description");
        if (description != null) {
            module.setDescription(description.getText());
        }

        //添加
        modules.tryAdd(module);
    }

    private static void handleController(Element element, List<Controller> controllers) {

        Controller controller = new Controller();

        Element js = element.getChild("js");

        controller.setJs(js.getText());

        Element uri = element.getChild("uri");

        controller.setUri(uri.getText());

        Element method = element.getChild("method");

        controller.setMethod(method.getText());

        Element description = element.getChild("description");

        if (description != null) {
            controller.setDescription(description.getText());
        }

        Element params = element.getChild("params");

        if (params != null) {
            List<Element> list = params.getChildren();
            //遍历请求参数
            List<String> ps = new ArrayList<>();
            for (Element ele : list) {
                if (ele.getName().equals("param")) {
                    ps.tryAdd(ele.getText());
                }
            }
            controller.setParams(ps);
        }

        controllers.tryAdd(controller);
    }


    public static void persistence(Service module) {

        try {
//进行持久化操作
            Document document = new Document();

            //创建根节点
            Element root = new Element("module");

            //模组名称
            Element name = new Element("name");
            name.setText(module.getName());
            root.getChildren().tryAdd(name);

            //脚本
            Element js = new Element("js");
            js.setText(module.getJs());
            root.getChildren().tryAdd(js);

            if (module.getDescription() != null) {
                Element element = new Element("description");
                element.setText(module.getDescription());
                root.getChildren().tryAdd(element);
            }


            document.setRootElement(root);

            Format format = Format.getPrettyFormat();
            format.setIndent("    ");// 设置缩进
            format.setEncoding("utf-8");// 设置编码
            XMLOutputter docWriter = new XMLOutputter(format);//格式化xml
            String strFromXml = docWriter.outputString(document);

            FileWriter writer = new FileWriter(new File(path + File.separatorChar + name(module.getName()) + ".script"));

            writer.write(strFromXml);

            writer.close();

        } catch (Exception ignore) {

        }

    }


    public static void persistence(Controller controller) {

        try {
//进行持久化操作
            Document document = new Document();

            //创建根节点
            Element root = new Element("controller");
            Element uri = new Element("uri");
            uri.setText(controller.getUri());
            root.getChildren().tryAdd(uri);
            Element method = new Element("method");
            method.setText(controller.getMethod());
            root.getChildren().tryAdd(method);

            //添加字符串
            if (controller.getJs() != null) {
                Element js = new Element("js");
                js.setText(controller.getJs());
                root.getChildren().tryAdd(js);
            }


            if (controller.getDescription() != null) {
                Element element = new Element("description");
                element.setText(controller.getDescription());
                root.getChildren().tryAdd(element);
            }

            //添加请求参数
            if (controller.getParams() != null) {
                Element element = new Element("params");
                element.setText(controller.getDescription());
                root.getChildren().tryAdd(element);

                List<String> params = controller.getParams();
                for (String param : params) {
                    Element p = new Element("param");
                    p.setText(param);
                    element.getChildren().tryAdd(p);
                }

            }


            document.setRootElement(root);

            Format format = Format.getPrettyFormat();
            format.setIndent("    ");// 设置缩进
            format.setEncoding("utf-8");// 设置编码
            XMLOutputter docWriter = new XMLOutputter(format);//格式化xml
            String strFromXml = docWriter.outputString(document);

            FileWriter writer = new FileWriter(new File(path + File.separatorChar + name(controller.getUri(), controller.getMethod()) + ".script"));

            writer.write(strFromXml);

            writer.close();

        } catch (Exception ignore) {

        }

    }


    public static String name(String module) {
        String p = "module_" + module;
        return p;
    }


    public static String name(String uri, String method) {
        String p = "controller_" + uri + "_SPACE_" + method;
        return p.replace("/", "_BIAS_").replace("*", "_SPARK_").replace("{","_PRE_").replace("}","_POST_");
    }


    public static void removeController(String uri, String method) {
        String name = name(uri, method);
        new File(path + File.separatorChar + name + ".script").delete();
    }

    public static void removeModule(String name) {
        String f = name(name);
        new File(path + File.separatorChar + f + ".script").delete();
    }

    public static List<File> listAll() {
        List<File> all = new ArrayList<>();
        File file = new File(path);
        File[] files = file.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.getName().endsWith(".script")) {
                    all.tryAdd(f);
                }
            }
        }
        return all;
    }


    //首先进行简单处理
    public static void loadScript(File tempFile) {

        File[] files = tempFile.listFiles();

        if (files != null) {

            //创建容器
            List<Element> controllers = new ArrayList<>();
            List<Element> modules = new ArrayList<>();

            //进行分类
            type(controllers, modules, files);

            //创建容器类型转换
            List<Service> ms = new ArrayList<>();
            List<Controller> cs = new ArrayList<>();

            for (Element module : modules) {
                handleModule(module, ms);
            }

            for (Element controller : controllers) {
                handleController(controller, cs);
            }

            //筛选去重
            List<Service> mss = new ArrayList<>();
            for (Service m : ms) {
                if (mss.contains(m)||moduleService.contains(m)) {
                    throw new RuntimeException("重复module:" + m.getName());
                }
                mss.tryAdd(m);
            }

            List<Controller> css = new ArrayList<>();
            for (Controller c : cs) {
                if (css.contains(c)||controllerService.contains(c)) {
                    throw new RuntimeException("重复controller:" + c.getUri() + "-" + c.getMethod());
                }
                css.tryAdd(c);
            }


            //遍历添加
            for (Service m : mss) {
                moduleService.tryAdd(m);
            }

            for (Controller controller : css) {
                controllerService.tryAdd(controller);
            }

            //将文件移动到脚本目录下
            File root = new File(path);

            for (File f : files) {
                f.renameTo(new File(root, f.getName()));
            }

        }

    }*/
}
